<?php

namespace app\common;
use think\facade\Db;

class Change
{
    public  function getInfo($id){
        $info = Db::name('doc_con')->find($id);
        return $info;
    }

    public function move($oldFlie='',$newFile='',$newPath=''){
        if (!is_dir($newPath)) {
            mkdir($newPath, 0755);
        }
        if (is_file($oldFlie)) {
            copy( $oldFlie,$newFile);
        }
//        @unlink($oldPath.$filename);
        return true;
    }

    public function run($id){
        $info = $this->getInfo($id);
        $newPath = root_path().'public/storage/wk_files/'.$id;
        $newPath = str_replace('/', DIRECTORY_SEPARATOR, $newPath);
        $oldPath = root_path().'public/storage/doc/';
        $oldPath = str_replace('/', DIRECTORY_SEPARATOR, $oldPath);
        $filename =$info['fileurl'];
        $oldFile = $oldPath.$filename;
        $file_type = strrchr($filename, '.');
        $base_name = $info['filename'];
//        $new_file_name = $base_name.$file_type;
        $newfile  = $newPath.DIRECTORY_SEPARATOR.$filename;
        $pdfname  = $newPath.DIRECTORY_SEPARATOR.$base_name.'.pdf';
        $jpgname  = $newPath.DIRECTORY_SEPARATOR.$base_name.'.jpg';

       if(!is_file($newfile))  $this->move($oldFile,$newfile,$newPath);
       if(!is_file($pdfname) && $file_type !='pdf') $this->toPdf($newfile,$pdfname);
       if(!is_file($jpgname)) $this->toJpg($pdfname,$jpgname);
       if(is_file($newfile) && is_file($pdfname) && is_file($jpgname)){
           $num = $this->getPageNum($pdfname);
           $newPath = $newPath.DIRECTORY_SEPARATOR;
           $dir_name = str_replace(root_path(), '', $newPath);
           $return_data=[
               'page'=>$num,
               'viewurl' =>$base_name.'.pdf',
               'imgurl' =>$base_name.'.jpg',
               'convert_status'=>2,
               'html' =>'storage/wk_files/'.$id.'/',
           ];
           $re =  Db::name('doc_con')->where('id',$id)->force(true)->save($return_data);
           if($re){
               unlink($oldPath.$filename);
               return 1;
           }else{
               return 0;
           }
        }

    }


    public function toPdf($file_name='',$pdfname=''){
//        $file =$file_path.DIRECTORY_SEPARATOR.$file_name;
        $cmd = 'python3 /var/www/html/boyanglee/topdf/DocumentConverter.py  '.$file_name.' '.$pdfname;
        if (function_exists('shell_exec')){
            shell_exec ($cmd );
        }
    }

    public function toJpg($pdfname,$jpgname){

        $cmd = 'python3 /var/www/html/boyanglee/topdf/pdf2jpg.py  '.$pdfname.' '.$jpgname;
        if (function_exists('shell_exec')){
            shell_exec ($cmd);
        }
    }

    public function getPageNum($pdfname){
        $pdftext = file_get_contents($pdfname);
        $num = preg_match_all("/\/Page\W/", $pdftext, $dummy);
        return $num;
    }

}